const wxPromise = require('../../util/wxPromise');
const { QNMPPlugin } = requirePlugin('QNBleApi');

// pages/normal-scale-ota/normal-scale-ota.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    connected: false,
    statusText: '',
    device: null,
    deviceInfo: null,
    binMap: {},
    // macInput: '04:AC:44:03:D4:07',
    macInput: 'D8:0B:CB:45:D5:61',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  bleEventListener() {
    /**
     * 监听扫描到设备的回调
     */
    const onBleDeviceFound = (device) => {
      if ((this.data.macInput && this.data.macInput === device.mac) || !this.data.macInput) {
        if (this.connecting) {
          console.log('当前正在连接，不再处理');
          return;
        }
        this.handleConnect(device);
      }
    };

    /**
     * 监听蓝牙断开连接的回调
     */
    const onDisconnected = (device) => {
      this.setData({
        connected: false,
        statusText: '设备连接已断开',
        device: null,
        deviceInfo: null,
      });
      this.connecting = false;
      console.log('设备连接已断开', device);
    };

    /**
     * 监听蓝牙状态发生变化回调，连接成功或断开连接都会出触发
     */
    const onBluetoothEnableChange = ({ available }) => {
      if (available) {
        this.setData({ statusText: '蓝牙可用，空闲' });
        // this.bleApi.startBleDeviceDiscovery();
      } else {
        this.setData({ statusText: '蓝牙不可用' });
      }
    };

    /**
     * 	监听设备连接成功回调
     */
    const onConnected = (device) => {
      console.log('哈哈哈', device);
      this.setData({ statusText: '已连接' });
      this.connecting = false;
      this.setData({
        connected: true,
      });
    };

    /**
     * 监听停止扫描的回调
     */
    const onStopDiscoveryDevice = () => {
      this.setData({
        statusText: '已停止扫描',
      });
    };

    /**
     * 监听开始扫描设备的回调
     */
    const onStartDiscoveryDevice = () => {
      this.setData({
        statusText: '开始扫描',
      });
    };

    return {
      onBleDeviceFound,
      onDisconnected,
      onBluetoothEnableChange,
      onConnected,
      onStopDiscoveryDevice,
      onStartDiscoveryDevice,
    };
  },

  initBle() {
    if (this.bleApi) {
      return this.bleApi;
    }

    // 初始化蓝牙
    this.bleApi = new QNMPPlugin({
      mpwx: wx, // 非必须 连接广播称时需要
      useSdk: false,
    });

    // 错误监听
    this.bleApi.onError = (err) => {
      console.error('捕捉到错误', err.detail);
    };

    // 初始化回调
    this.bleApi.onReady = ({
      bleEnableState, //表示当前蓝牙是否为开启状态
    }) => {
      if (bleEnableState) {
        this.bleApi.startBleDeviceDiscovery(); 
      } else {
        console.log('蓝牙状态为关闭');
      }
    };

    // 设置蓝牙监听事件
    this.bleApi.setBleEventListener(this.bleEventListener());

    // 初始化
    this.bleApi.init();

    return this.bleApi;
  },

  deviceEventListener() {
    const onGetDeviceInfo = (deviceInfo) => {
      this.setData({ deviceInfo });
    };

    return {
      onGetDeviceInfo,
    };
  },

  restart() {
    this.bleApi
      .stop()
      .then(() => {
        this.setData({
          connected: false,
        });
        this.bleApi.startBleDeviceDiscovery();
      })
      .catch((err) => {
        console.log('停止扫描失败', err);
      });
  },

  async handleConnect(device) {
    this.setData({ device });
    this.connecting = true;
    const user = {
      height: 170,
      gender: 1,
      birthday: '1994-01-02',
    };

    /**
     * 调用连接成功后，会返回本次连接的设备访问对象，可以对设备进行一些蓝牙数据通讯
     * 每次连接返回的都不一样，连接成功后，该对象开始可以操作，连接失败或断开后，该对象会失效
     */
    console.log('要连接的对象', device);
    this.deviceHandler = await this.bleApi.createBleConnection(device, this.deviceEventListener(), {
      user,
    });
  },

  onConnectButtonClick() {
    this.connecting = false;
    if (!this.bleApi) {
      this.initBle();
    } else if (this.data.connected) {
      this.restart();
    } else {
      this.bleApi.startBleDeviceDiscovery();
    }
  },

  async requestBin(url) {
    try {
      if (this.data.binMap[url]) {
        return this.data.binMap[url];
      }

      wx.showLoading({ title: '请求资源包中...' });

      const requestResult = await wxPromise(wx.request)({
        url,
        method: 'GET',
        responseType: 'arraybuffer',
      });
  
      if (requestResult.statusCode !== 200) {
        throw new Error(requestResult);
      }

      this.setData({ binMap: { ...this.data.binMap, [url]: requestResult.data } });

      wx.hideLoading();

      return requestResult.data;
    } catch (error) {
      wx.hideLoading();
      console.error(error);

      if (error instanceof Error) {
        wx.showModal({
          title: '错误提示',
          content: error.message,
          showCancel: false,
        });
      } else {
        const title = error?.error || error?.err_msg || '发生了错误';
        const content = error?.error_description || error?.err_detail || error?.errMsg || `${error}`;
        wx.showModal({
          title,
          content,
          showCancel: false,
        });
      }

      throw error;
    }
  },

  async doOta(url) {
    if (!this.data.connected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none',
      });

      return;
    }

    const ab = await this.requestBin(url);

    try {
      wx.showLoading({
        title: '传输数据中...',
      });
      const otaStartTime = Date.now();
      
      await this.bleApi.callProtocolMethod(this.data.device.deviceId, 'doOta', [ab]);

      const otaEndTime = Date.now();
      const otaTimeDiffSeconds = Math.floor((otaEndTime - otaStartTime) / 1000);
      console.info('ota更新所花费时间为', otaTimeDiffSeconds, '秒，大概', Math.floor(otaTimeDiffSeconds / 60), '分钟');
      
      wx.hideLoading();
      wx.showToast({
        title: '更新完成',
        icon: 'success',
      })
    } catch (error) {
      console.error(error);
      wx.hideLoading();
      wx.showToast({
        title: '传输数据失败',
      })
    }
  },

  async upgradeButtonClick() {
    await this.doOta('http://qnplus-preview.glb.qnniu.com/normal-scale-ota/COM201D1X-B-AX-H53-7769H-3E36H.bin');
  
  },

  async fallbackButtonClick() {
    await this.doOta('http://qnplus-preview.glb.qnniu.com/normal-scale-ota/COM201D1X-B-YOL-H49-4DE2H-0932H.bin');
  },
})